package org.ktx.osr.service

import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.WindowManager
import android.util.Log
import org.ktx.osr.widget.FloatingControlWidget
import org.ktx.osr.util.skipScreenShot

/**
 * 浮动控件管理器
 * 负责管理录制过程中的浮动控制控件
 * 功能边界：仅处理浮动控件的显示和交互，不涉及录制逻辑
 */
class FloatingWidgetManager(private val context: Context) {
    private val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private var floatingControlWidget: FloatingControlWidget? = null
    private var isWidgetVisible = false

    companion object {
        private const val TAG = "FloatingWidgetManager"
    }

    /**
     * 显示浮动控件
     */
    fun showWidget(
        onToggleRecording: () -> Unit,
        onStopRecording: () -> Unit
    ): Boolean {
        if (isWidgetVisible) {
            Log.w(TAG, "Widget already visible")
            return true
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            Log.w(TAG, "Floating widget not supported on this Android version")
            return false
        }

        return try {
            floatingControlWidget = FloatingControlWidget(context).apply {
                setOnToggleRecordingListener { onToggleRecording() }
                setOnStopListener { onStopRecording() }
            }

            val params = WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
            )

            params.gravity = Gravity.TOP or Gravity.START
            params.x = 0
            params.y = 100

            windowManager.addView(floatingControlWidget, params)
            
            // 防止截图
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                floatingControlWidget?.let {
                    it.post { it.skipScreenShot() }
                }
            }

            isWidgetVisible = true
            Log.d(TAG, "Floating widget shown successfully")
            true
        } catch (e: Exception) {
            Log.e(TAG, "Failed to show floating widget", e)
            hideWidget()
            false
        }
    }

    /**
     * 隐藏浮动控件
     */
    fun hideWidget() {
        if (!isWidgetVisible) return

        try {
            floatingControlWidget?.let { widget ->
                if (widget.isAttachedToWindow) {
                    windowManager.removeView(widget)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error hiding floating widget", e)
        } finally {
            floatingControlWidget = null
            isWidgetVisible = false
            Log.d(TAG, "Floating widget hidden")
        }
    }

    /**
     * 更新录制状态
     */
    fun updateRecordingState(state: Int) {
        floatingControlWidget?.updateRecordingState(state)
    }

    /**
     * 设置录制时长
     */
    fun setRecordingDuration(duration: String) {
        floatingControlWidget?.setRecordingDuration(duration)
    }

    /**
     * 检查控件是否可见
     */
    fun isWidgetVisible(): Boolean = isWidgetVisible
}
